package com.qf.security1.conf;

import com.alibaba.fastjson.JSON;
import com.qf.security1.domain.Code;
import com.qf.security1.domain.R;
import com.qf.security1.domain.Resources;
import com.qf.security1.filters.LoginFilter;
import com.qf.security1.filters.VerifyTokenFilter;
import com.qf.security1.mapper.ResourcesMapper;
import com.qf.security1.utils.MD5Utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import sun.plugin2.applet.context.NoopExecutionContext;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements InitializingBean {

    @Autowired
    private ResourcesMapper resourcesMapper;

    //所有资源及其需要的权限信息
    private List<Resources> resources;

    @Override
    public void afterPropertiesSet() throws Exception {
        resources = resourcesMapper.findAll();
    }


    public static void main(String[] args) {
        //盐值
        String hashpw = BCrypt.hashpw("123", BCrypt.gensalt());
        System.out.println(hashpw);

        //在原始密码的基础上，混淆一些内容，参与混淆的内容称之为盐值，这个动作叫加盐
//        String md5 = MD5Utils.md5("1a2b3");
//        System.out.println(md5);
    }

    /**
     * 向spring容器中注入一个密码加密器
     *  作用：是对页面上的明文密码进行加密处理，将处理后的密文和数据库中查出来的密文进行比对
     *      必须和数据库的密码处理一致
     */
    @Bean
    public PasswordEncoder pwe(){
        //数据库的密码不加密，这里返回的也应该是一个不加密的PasswordEncoder
        //return NoOpPasswordEncoder.getInstance();

        //数据库的密码是经过BCrypt加密处理的，这里返回的也应该是一个BCrypt密码加密器
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //放开跨站访问的控制(如果不放开，security要求只能访问它内部自己的页面)
        http.csrf().disable();

        //配置跨域访问
        http.cors().configurationSource(cosr());

        //配置需要登录的资源，哪些资源需要权限
        for (Resources res : resources) {
            String url = res.getUrl();
            List<String> roles = res.getRoles();
            http.authorizeRequests().antMatchers(url).hasAnyRole(roles.toArray(new String[0]));
        }

        http.authorizeRequests()
                // 访问/user/**下的所有资源都要求认证（登录-authenticated）
//                .antMatchers("/user/**").authenticated()
                // hasRole 相当于是要登录，同时要权限。这里要求的是P1角色权限
//                .antMatchers("/user/**").hasRole("P1")
//                .antMatchers("/person/**").hasRole("P2")
                // 除了上述配置的资源需要认证外，其他所有资源都允许访问（permitAll）
                .antMatchers("/**").permitAll();

        //添加未登录的回调处理(当访问资源需要登录，但是没有登录的情况下，会回调这个方法（commence）)
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

                response.setContentType("application/json;charset=utf-8");

                R r = R.error("尚未登录", Code.NOT_LOGIN);
                String jsonStr = JSON.toJSONString(r);

                response.getWriter().write(jsonStr);
            }
        }).accessDeniedHandler(new AccessDeniedHandler() { //当访问的资源需要权限但是没有权限时，会触发这个回调
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                response.setContentType("application/json;charset=utf-8");

                R r = R.error("无权访问", Code.NO_AUTH);
                String jsonStr = JSON.toJSONString(r);

                response.getWriter().write(jsonStr);
            }
        });

        //设置我们自己的登录认证过滤器
        http.addFilter(new LoginFilter(authenticationManager()))
                //认证token的过滤器
                .addFilter(new VerifyTokenFilter(authenticationManager()));
    }

    /**
     * 返回一个跨域访问配置源对象
     * @return
     */
    private CorsConfigurationSource cosr() {
        UrlBasedCorsConfigurationSource cors = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();

        //允许所有域的访问 (当setAllowCredentials设置为true时，origins不允许配置为*，必须指定具体允许的域（前端资源所在的域）是什么)
        config.setAllowedOrigins(Arrays.asList("http://localhost"));
        //允许任何请求头信息的携带（不包含cookie的）
        config.setAllowedHeaders(Arrays.asList("*"));
        //允许任何响应头信息的携带
        config.setExposedHeaders(Arrays.asList("*"));
        //允许任意请求方式（get、post、put、delete）
        config.setAllowedMethods(Arrays.asList("*"));
        //允许请求发送时，携带认证信息（比如cookie）
        config.setAllowCredentials(true);

        //所有的URL路径访问，都采用指定的配置进行跨域设置
        cors.registerCorsConfiguration("/**",config);

        return cors;
    }
}
